package com.neusof.db;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.neusof.bean.EmpBean;
import com.neusof.utils.MyUtil;

public class DBDataSource {

	private static DataSource mDataSource;

	private DBDataSource() {
	}

	public static DataSource getDataSource() {
		if (mDataSource == null) {
			try {
				// 使用工具类Properties 读取配置文件
				Properties pro = new Properties();
				// 工具类Properties加载配置文件:要求必须在src根目录下，不能在包中，否则找不到配置文件
				// 将配置文件内容读取并转入输入了对象
				InputStream stream = DBDataSource.class.getClassLoader().getResourceAsStream("db.properties");
				// 把配置文件内容的输入了对象加载到工具类Properties的实例对象中
				pro.load(stream);
				// 初始化数据源对象，使用dbcp2中BasicDataSourceFactory工厂类的createDataSource的方法获取实例对象
				mDataSource = BasicDataSourceFactory.createDataSource(pro);
			} catch (Exception e) {
				MyUtil.mRootLogger.debug("数据源初始化异常：" + e.getMessage());
				e.printStackTrace();
			}
		}
		return mDataSource;
	}

	public static void main(String[] args) {
		try {
			QueryRunner queryRunner = new QueryRunner(getDataSource());
			String sql = "select * from emp";
			List<EmpBean> query = queryRunner.query(sql, new BeanListHandler<>(EmpBean.class));
			for (EmpBean empBean : query) {
				System.out.println(empBean.toString());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
